package com.hotel.security.service.impl;

import com.hotel.dao.user.UserMapper;
import com.hotel.entity.User;
import com.hotel.security.model.LoginUser;
import com.hotel.security.model.RedisCache;
import com.hotel.security.service.LoginService;
import com.hotel.util.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;
    @Resource
    private PasswordEncoder passwordEncoder;

    public Object login(User user) {
        //AuthenticationManager authenticationManager 来进行用户验证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserLoginName(),user.getUserPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果验证没成功给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        //如果成功了,把用户的userid生成jwt并存入ResponseResult进行返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userLoginName = loginUser.getUser().getUserLoginName();
        String jwt = JwtUtil.createToken(userLoginName);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", jwt);
        resultMap.put("loginUser", loginUser);
        //把完整的用户信息存入redis,userid来作为key
        redisCache.setCacheObject(userLoginName, loginUser);
        return resultMap;
    }


}
